const Koa = require('koa')
const path = require('path')
const bodyParser = require('koa-body')
const koaStatic = require('koa-static');
const koaCors = require('koa-cors')
const app = new Koa()
const { port } = require('./models/defaultConfig.js')
app.use(koaStatic(path.join(__dirname, './public')));
const userRouter = require('./routers/user.js')
const dataRouter = require('./routers/data.js');
const { error } = require('console');
// 请求体 parse 中间件，用于 parse json 格式请求体
app.use(bodyParser(
    {
        multipart: true,
        formidable: {
            maxFileSize: 2 * 1024 * 1024, // 默认2M
            uploadDir: path.resolve(__dirname, './public'),// 可以填一个路径
        },
    }
));

// 跨域操作
app.use(koaCors())

// app.all('*', function (ctx, next) {
//     ctx.res.header('Access-Control-Allow-Origin', '*');
//     ctx.res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, content-Type, Accept, Authorization');
//     ctx.res.header('Access-Control-Allow-Methods', '*');
//     ctx.res.header('Content-Type', 'application/json;charset=utf-8; multipart/form-data');
//     next();
// });

// 白名单
app.use(async (ctx, next) => {
    let webEnv
    if (app.env === 'development') {
        webEnv = 'localhost'
    } else {
        webEnv = '116.62.149.160'
    }
    // console.log( webEnv, '----',ctx.header);
    // ctx.header.origin.indexOf(webEnv) !== -1
    if (true) {
        await next()
    } else {
        ctx.body = {
            data: null,
            flag: false,
            code: 403,
            msg: '权限不够~'
        }
    }
})

app.use(async (ctx, next) => {
    await next()
    ctx.body = {
        data: ctx.body?.data ? ctx.body.data : ctx.body,
        msg: ctx.msg ? ctx.msg : null,
        code: ctx.code ? ctx.code : 200,
        flag: ctx.flag ? ctx.flag : true
    }
})

// user路由
app.use(userRouter)

// data路由
app.use(dataRouter)

app.listen(port, function () {
    console.log(`app is listenling at port ${port}`);
});
app.on('error', (err) => {
    console.log('server error', err);
})